<template>
  <div class="rights">
    <!-- 面包屑 -->
    <el-breadcrumb
      separator="/"
      style="line-height:45px;" >
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 添加用户按钮 -->
    <el-button
      type="success"
      plain
      @click="adddialogFormVisible=true"
    >添加角色</el-button>
    <!-- 角色列表 -->
    <template>
      <el-table
        :data="rolesList"
        style="width: 100%;margin-top:15px;"
        border >
        <el-table-column type="expand">
          <!-- 展开行 -->
          <template slot-scope="scope">
            <!-- scope.row.children展开行数据源 -->
            <el-row
              v-for="first in scope.row.children"
              :key="first.id" >
              <el-col :span="4">
                <div class="grid-content bg-purple">
                  <el-tag
                    closable
                    type="success"
                    @close='removeRight(scope.row,first.id)'
                  >
                    {{first.authName}}
                  </el-tag>
                </div>
              </el-col>
              <el-col :span="20">
                <div class="grid-content bg-purple-light">
                  <el-row
                    v-for="second in first.children"
                    :key="second.id"
                  >
                    <el-col :span="4">
                      <div class="grid-content bg-purple">
                        <el-tag
                          closable
                          type="info"
                          @close='removeRight(scope.row,second.id)'
                        >
                          {{second.authName}}
                        </el-tag>
                      </div>
                    </el-col>
                    <el-col :span="20">
                      <div class="grid-content bg-purple-light">
                        <el-tag
                          v-for="third in second.children"
                          :key="third.id"
                          closable
                          type="warning"
                          @close='removeRight(scope.row,third.id)'
                        >
                          {{third.authName}}
                        </el-tag>
                      </div>
                    </el-col>
                  </el-row>
                </div>
              </el-col>
            </el-row>
            <span v-show='scope.row.children.length === 0'>没有相关权限，请前往授权</span>

          </template>
        </el-table-column>
        <el-table-column
          type="index"
          width="50"
        >
        </el-table-column>
        <el-table-column
          label="角色名称"
          prop="roleName"
        >
        </el-table-column>
        <el-table-column
          label="描述"
          prop="roleDesc"
        >
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip
              content="编辑"
              placement="top"
            >
              <el-button
                size="mini"
                type="info"
                icon="el-icon-edit"
                plain
                @click="handleEdit(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              content="删除"
              placement="top"
            >
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                plain
                @click="handleDelete(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              content="角色分配"
              placement="top"
            >
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-share"
                plain
                @click="grantRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 添加角色 -->
    <el-dialog
      title="添加角色"
      :visible.sync="adddialogFormVisible" >
      <el-form
        :model="addform"
        :rules="rules"
        ref="addform"
        label-width="100px"
      >
        <el-form-item
          label="角色名称"
          prop="roleName"
        >
          <el-input v-model="addform.roleName"></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="roleDesc"
        >
          <el-input
            v-model="addform.roleDesc"
            auto-complete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="adddialogFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addRole('addform')"
        >确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑角色 -->
    <el-dialog
      title="编辑用户信息"
      :visible.sync="editdialogFormVisible" >
      <el-form
        :model="editform"
        ref="editform"
        label-width="100px"
      >
        <el-form-item
          label="角色名称"
          prop='roleName'
        >
          <el-input
            v-model="editform.roleName"
            auto-complete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          label-width="100px"
          prop='roleDesc'
        >
          <el-input
            v-model="editform.roleDesc"
            auto-complete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editdialogFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="editRole"
        >确 定</el-button>
      </div>
    </el-dialog>
    <!-- 角色授权 -->
    <el-dialog
      title="角色授权"
      :visible.sync="grantdialogFormVisible" >
      <div class="box">
        <el-tree
          ref="tree"
          :data="grantList"
          show-checkbox
          node-key="id"
          :default-expand-all='true'
          :default-checked-keys="selectedNode"
          :props="defaultProps"
        >
        </el-tree>
      </div>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="grantdialogFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="grantSubmit"
        >确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { grentList, addRole, editRole, deleteRole, getRightList, grantRightForRole, deleteRightByRoleId } from '@/api'
export default {
  data () {
    return {
      // 角色列表
      rolesList: [],
      // 添加角色
      addform: {
        roleName: '',
        roleDesc: ''
      },
      // 编辑角色信息
      editform: {
        roleName: '',
        roleDesc: '',
        id: ''
      },
      // 控制添加角色的显示与否
      adddialogFormVisible: false,
      // 控制编辑角色的显示与否
      editdialogFormVisible: false,
      // 控制授权角色的显示与否
      grantdialogFormVisible: false,
      // 输入框的长度
      labelWidth: '200',
      // 规则
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      // 授权
      grantList: [],
      // 设置当前属性值
      defaultProps: {
        children: 'children', // 找子元素
        label: 'authName' // 显示什么
      },
      // 勾选节点的默认数组
      selectedNode: [],
      // 授权id
      roleId: ''
    }
  },
  methods: {
    // 显示编辑角色信息的弹框
    handleEdit (row) {
      // console.log(row)
      // 显示编辑的弹框
      this.editdialogFormVisible = true
      // 将对应数据显示在页面上
      this.editform.roleName = row.roleName
      this.editform.roleDesc = row.roleDesc
      this.editform.id = row.id
    },
    // 实现删除角色的功能
    handleDelete (row) {
      // console.log(row)
      // 调用接口，实现角色的删除功能
      deleteRole(row.id).then(res => {
        // console.log(res)
        if (res.meta.status === 200) {
          // 给出提示
          this.$message.success('角色删除成功')
          // 重新渲染数据
          this.init()
        } else {
          // 给出提示
          this.$message.error('角色删除失败')
        }
      })
    },
    // 封装实现数据渲染功能
    init () {
      // 实现角色列表渲染功能
      grentList().then(res => {
        // console.log(res)
        if (res.meta.status === 200) {
          // 将数据渲染出来
          this.rolesList = res.data
        }
      })
    },
    // 实现角色添加功能
    addRole (roleForm) {
      this.$refs[roleForm].validate(valid => {
        if (valid) {
          // 调用接口，实现角色添加
          addRole(this.addform).then(res => {
            // console.log(res)
            if (res.meta.status === 201) {
              // 给出提示
              this.$message({
                type: 'success',
                message: res.meta.msg
              })
              // 隐藏添加角色框
              this.adddialogFormVisible = false
              // 重新渲染数据
              this.init()
            } else {
              // 给出提示
              this.$message({
                type: 'error',
                message: res.meta.msg
              })
            }
          })
        } else {
          // 给出提示
          this.$message('输入数据不完整')
          return false
        }
      })
    },
    // 实现角色信息的编辑功能
    editRole () {
      // 调用接口，实现角色信息的编辑
      editRole(this.editform).then(res => {
        console.log(res)
        if (res.meta.status === 200) {
          // 给出提示
          this.$message.success('角色信息编辑成功')
          // 隐藏弹框
          this.editdialogFormVisible = false
          // 重新渲染页面
          this.init()
        } else {
          this.$message.error('角色信息编辑失败')
        }
      })
    },
    // 显示授权角色弹框
    grantRole (row) {
      // console.log(row)
      // 显示授权弹框
      this.grantdialogFormVisible = true
      // 获取授权id
      this.roleId = row.id
      // 调用接口，将授权信息展示出来
      getRightList('tree')
        .then(res => {
          // console.log(res)
          if (res.meta.status === 200) {
            this.grantList = res.data
          }
        })
        // 默认选中为0个
      this.selectedNode.length = 0
      // 获取当前角色所有的权限id  遍历每一项
      row.children.forEach((first, index) => {
        if (first.children && first.children.length > 0) {
          first.children.forEach((second, index) => {
            if (second.children && second.children.length > 0) {
              second.children.forEach((third, index) => {
                this.selectedNode.push(third.id)
              })
            }
          })
        }
      })
    },
    // 实现角色授权功能
    grantSubmit () {
      // 获取子节点及其对应的父节点 -- 得到对象数组
      var selectedNodes = this.$refs.tree.getCheckedNodes()
      // 遍历对象数组  ["105,104,101","116,104,101"]
      // map 方法是用于循环，类似forEach，它的返回值是一个数组
      var nodes = selectedNodes.map((value, index) => {
        // 将该节点id以及其父节点id返回
        return value.id + ',' + value.pid
      })
      // 将数组转为字符串
      var joinStr = nodes.join(',')
      // 去掉重复的
      var set = new Set(joinStr.split(','))
      // 将set对象成员值转换为数组，利用Array.from将Set结构转换成数组
      var finalArr = Array.from(set)
      // 将数组转为字符串
      var finalRid = finalArr.join(',')
      // 调用接口，实现角色权限的修改
      grantRightForRole(this.roleId, finalRid)
        .then(res => {
          // console.log(res)
          if (res.meta.status === 200) {
            this.$message.success('更新权限成功')
            // 隐藏弹框
            this.grantdialogFormVisible = false
            // 重新渲染页面
            this.init()
          }
        })
    },
    // 下拉 删除权限
    removeRight (row, rightid) {
      // 调用接口，实现权限删除
      deleteRightByRoleId(row.id, rightid)
        .then(res => {
          // console.log(res)
          if (res.meta.status === 200) {
            // 给出提示
            this.$message({
              type: 'success',
              message: res.meta.msg
            })
            // 赋值 局部渲染数据
            row.children = res.data
          } else {
            this.$message({
              type: 'warning',
              message: res.meta.msg
            })
          }
        })
    }
  },
  mounted () {
    this.init()
  }
}
</script>
<style lang="scss" scoped>
.box {
  height: 300px;
  overflow: auto;
}
.el-tag {
  margin: 0 5px 10px;
}
</style>
